# src/views/pages/appointment_page.py 功能说明
"""
预约管理模块
"""
from PySide6.QtWidgets import (QVBoxLayout, QHBoxLayout, QTableWidget,
                               QTableWidgetItem, QHeaderView, QPushButton, QMessageBox,
                               QDateTimeEdit, QComboBox, QDialog, QFormLayout, QLabel,
                               QLineEdit, QMenu, QWidget, QApplication)
from PySide6.QtCore import Qt, QDateTime, QSize
from PySide6.QtGui import QColor, QIcon, QPixmap, QCursor
from utils.db import db
from .base_page import BasePage
import math
from pathlib import Path
import sqlite3
from datetime import datetime


class AppointmentPage(BasePage):
    def __init__(self, current_user):
        super().__init__()
        self.current_user = current_user
        self.current_page = 1  # 添加分页参数初始化
        self.setup_ui()
        self.load_appointments()
        self.apply_styles()
        # self.delete_all_appointments()

    def setup_ui(self):
        layout = QVBoxLayout()

        # 操作栏
        action_bar = QHBoxLayout()
        action_bar.setContentsMargins(0, 0, 0, 15)

        # 左侧区域 - 新建预约按钮
        left_area = QHBoxLayout()
        left_area.setAlignment(Qt.AlignLeft)  # 左对齐
        self.new_btn = QPushButton("新建预约")
        self.new_btn.clicked.connect(self.show_create_dialog)
        self.new_btn.setFixedSize(100, 30)
        self.new_btn.setStyleSheet("""
            QPushButton {
                background-color: #4a90e2; 
                color: white;
                border-radius: 4px;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
        """)
        left_area.addWidget(self.new_btn)

        # 右侧区域 - 搜索条件+按钮
        right_area = QHBoxLayout()
        right_area.setAlignment(Qt.AlignRight)
        right_area.setSpacing(15)  # 从8增加到15
        right_area.setContentsMargins(0, 0, 10, 0)  # 右侧添加边距

        # 搜索条件组（姓名、电话、状态）
        search_conditions = QHBoxLayout()
        search_conditions.setSpacing(15)
        search_conditions.setContentsMargins(0, 0, 0, 0)  # 移除内边距
        search_conditions.addStretch(1)  # 在最后添加伸缩项

        # 姓名搜索
        name_group = QHBoxLayout()
        name_group.setSpacing(5)
        name_group.setContentsMargins(0, 0, 0, 0)
        name_label = QLabel("姓名:")
        name_label.setFixedWidth(40)  # 固定标签宽度
        self.name_search = QLineEdit()
        self.name_search.setPlaceholderText("输入姓名")
        self.name_search.setFixedSize(150, 28)  # 加长并增加高度
        self.name_search.setStyleSheet("""
            QLineEdit {
                border: 1px solid #d0d0d0;
                border-radius: 4px;
                padding: 6px 8px;  /* 增加内边距 */
                font-size: 13px;
                background: white;
                min-width: 150px;  /* 设置最小宽度 */
            }
        """)
        name_group.addWidget(name_label)
        name_group.addWidget(self.name_search)
        search_conditions.addLayout(name_group)

        # 电话搜索
        phone_group = QHBoxLayout()
        phone_group.setSpacing(5)
        phone_group.setContentsMargins(0, 0, 0, 0)
        phone_label = QLabel("电话:")
        phone_label.setFixedWidth(40)  # 固定标签宽度
        self.phone_search = QLineEdit()
        self.phone_search.setPlaceholderText("输入电话")
        self.phone_search.setFixedSize(150, 28)
        self.phone_search.setStyleSheet("""
            QLineEdit {
                padding: 6px 8px;
                border: 1px solid #d0d0d0;
                border-radius: 4px;
                font-size: 13px;
                background: white;
                min-width: 150px;
            }
        """)
        phone_group.addWidget(phone_label)
        phone_group.addWidget(self.phone_search)
        search_conditions.addLayout(phone_group)

        # 状态筛选
        status_group = QHBoxLayout()
        status_group.setSpacing(5)
        status_group.setContentsMargins(0, 0, 0, 0)
        status_label = QLabel("状态:")
        status_label.setFixedWidth(40)  # 固定标签宽度
        self.status_filter = QComboBox()
        self.status_filter.addItems(["全部", "待确认", "已确认", "已完成"])
        self.status_filter.setFixedSize(150, 28)  # 高度从32改为28
        self.status_filter.setStyleSheet("""
            QComboBox {
                border: 1px solid #d0d0d0;
                border-radius: 4px;
                padding: 6px 8px;  /* 增加内边距 */
                font-size: 13px;
                background: white;
                min-width: 150px;
                min-height: 14px;
            }
            QComboBox::drop-down {
                width: 18px;
                background: transparent;
            }
        """)
        status_group.addWidget(status_label)
        status_group.addWidget(self.status_filter)
        search_conditions.addLayout(status_group)

        # 搜索按钮
        search_btn = QPushButton("搜索")
        search_btn.clicked.connect(self.load_appointments)
        search_btn.setFixedSize(80, 28)  # 高度从32改为28
        search_btn.setStyleSheet("""
            QPushButton {
                background-color: #34c759;
                color: white;
                border-radius: 4px;
                font-size: 13px;
                border: none;
                padding: 4px 12px;  /* 减少垂直内边距 */
                min-width: 80px;
                min-height: 22px; 
            }
            QPushButton:hover {
                background-color: #2da44e;
            }
            QPushButton:pressed {
                background-color: #248f43;
            }
        """)

        right_area.addLayout(search_conditions)
        right_area.addWidget(search_btn)  # 按钮紧接搜索条件

        # 组合左右区域
        action_bar.addLayout(left_area)
        action_bar.addStretch(1)  # 添加伸缩项撑开空间
        action_bar.addLayout(right_area)

        layout.addLayout(action_bar)

        # 预约表格
        self.table = QTableWidget()
        self.table.setObjectName("appointmentTable")
        self.table.setMinimumSize(800, 600)  # 设置最小尺寸保证内容展示
        self.table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #e0e0e0;
                background-color: white;
                min-width: 800px;
                gridline-color: #f0f0f0;
                font-size: 13px;  /* 统一字体大小 */
            }
            QTableWidget::item {
                padding: 8px;
                border-bottom: 1px solid #f0f0f0;  /* 添加行分隔线 */
            }
        """)
        self.table.setColumnCount(8)
        self.table.setHorizontalHeaderLabels(["ID", "客户姓名", "联系电话", "服务项目", "预约时间", "理发师", "状态", "操作"])
        header = self.table.horizontalHeader()

        # 设置列宽策略
        column_config = [
            (0, 80, QHeaderView.Fixed),    # ID
            (1, 150, QHeaderView.ResizeToContents),  # 姓名（加宽）
            (2, 150, QHeaderView.ResizeToContents),  # 电话
            (3, 250, QHeaderView.Stretch),  # 服务项目（加宽）
            (4, 180, QHeaderView.ResizeToContents),  # 时间
            (5, 150, QHeaderView.ResizeToContents),  # 理发师
            (6, 100, QHeaderView.ResizeToContents),  # 状态
            (7, 260, QHeaderView.Fixed)    # 操作（加宽以适应按钮）
        ]

        for col, width, mode in column_config:
            self.table.setColumnWidth(col, width)
            header.setSectionResizeMode(col, mode)

        # 表格其他设置
        self.table.verticalHeader().setVisible(False)
        self.table.setAlternatingRowColors(True)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)

        layout.addWidget(self.table)

        self.setLayout(layout)

    def load_appointments(self):
        try:
            # 获取搜索条件
            name = self.name_search.text().strip()
            phone = self.phone_search.text().strip()
            status = self.status_filter.currentText()

            # 构建查询条件
            conditions = []
            params = []

            if name:
                conditions.append("customer_name LIKE ?")
                params.append(f"%{name}%")
            if phone:
                conditions.append("phone_number LIKE ?")
                params.append(f"%{phone}%")
            if status != "全部":
                conditions.append("status = ?")
                params.append(status.lower())

            # 如果没有条件，返回所有预约
            if not conditions:
                conditions.append("1=1")  # 返回所有数据

            # 修改后的基础查询语句
            base_query = """
                SELECT 
                    a.id AS id,
                    a.customer_name AS customer_name,
                    a.phone_number AS phone_number,
                    a.service_type AS service_type,
                    strftime('%Y-%m-%d %H:%M', a.appointment_time) AS appointment_time,
                    COALESCE(u.display_name, '未分配') AS barber_name,
                    a.status AS status,
                    a.barber_id AS barber_id
                FROM appointments a
                LEFT JOIN users u ON a.barber_id = u.id
                {where}
                ORDER BY a.appointment_time DESC
            """

            where_clause = "WHERE " + " AND ".join(conditions) if conditions else ""

            # 获取预约数据
            self.table.setRowCount(0)  # 清空旧数据
            loading_label = QLabel("正在加载数据...")
            loading_label.setAlignment(Qt.AlignCenter)
            self.table.setRowCount(1)
            self.table.setCellWidget(0, 0, loading_label)
            self.table.setSpan(0, 0, 1, self.table.columnCount())
            appointments = db.fetch_all(base_query.format(where=where_clause), params)

            # 在填充数据时添加调试信息
            print(f"获取到预约数据：{len(appointments)}条")
            if not appointments:
                self.table.setRowCount(1)
                self.table.setItem(0, 0, QTableWidgetItem("暂无数据"))
                self.table.setSpan(0, 0, 1, self.table.columnCount())
                return

            for row, appt in enumerate(appointments):
                self.table.insertRow(row)
                print(f"第{row}行数据：{dict(appt)}")  # 打印原始数据
                self.table.setItem(row, 0, QTableWidgetItem(str(appt['id'])))
                self.table.setItem(row, 1, QTableWidgetItem(appt['customer_name']))
                self.table.setItem(row, 2, QTableWidgetItem(appt['phone_number']))
                self.table.setItem(row, 3, QTableWidgetItem(appt['service_type']))
                appt_time = appt['appointment_time'].replace(' ', '\n')
                self.table.setItem(row, 4, QTableWidgetItem(appt_time))
                self.table.setItem(row, 5, QTableWidgetItem(appt['barber_name']))

                # 检查当前时间与预约时间的关系
                appointment_time = QDateTime.fromString(appt['appointment_time'], "yyyy-MM-dd HH:mm")
                current_time = QDateTime.currentDateTime()

                # 设置状态
                if current_time > appointment_time:
                    # 如果当前时间大于预约时间，设置状态为已完成
                    self.table.setItem(row, 6, QTableWidgetItem("已完成"))
                    # 禁用编辑和完成按钮
                    edit_button = QPushButton("编辑")
                    edit_button.setEnabled(False)  # 禁用
                    complete_button = QPushButton("完成")
                    complete_button.setEnabled(False)  # 禁用
                else:
                    # 否则，允许编辑和状态修改
                    self.table.setItem(row, 6, QTableWidgetItem(appt['status']))  # 显示当前状态
                    edit_button = QPushButton("编辑")
                    edit_button.setStyleSheet("""
                        QPushButton {
                            min-width: 60px;
                            max-width: 80px;
                            padding: 4px 8px;
                            font-size: 12px;
                        }
                    """)
                    edit_button.setStyleSheet(edit_button.styleSheet() + "background-color: #3498db; color: white;")
                    edit_button.clicked.connect(lambda _, id=appt['id']: self.edit_appointment(id))

                    complete_button = QPushButton("完成")
                    complete_button.setStyleSheet("""
                        QPushButton {
                            min-width: 60px;
                            max-width: 80px;
                            padding: 4px 8px;
                            font-size: 12px;
                        }
                    """)
                    complete_button.setStyleSheet(complete_button.styleSheet() +
                                                  "background-color: #2ecc71; color: white;")
                    complete_button.clicked.connect(lambda _, id=appt['id']: self.update_status(id, "已完成"))

                delete_button = QPushButton("删除")
                delete_button.setStyleSheet("""
                    QPushButton {
                        min-width: 60px;
                        max-width: 80px;
                        padding: 4px 8px;
                        font-size: 12px;
                    }
                """)
                delete_button.setStyleSheet(delete_button.styleSheet() + "background-color: #e74c3c; color: white;")
                delete_button.clicked.connect(lambda _, id=appt['id']: self.delete_appointment(id))

                # 添加按钮到操作列
                button_layout = QHBoxLayout()
                button_layout.setContentsMargins(5, 2, 5, 2)  # 减少边距
                button_layout.setSpacing(8)  # 增加按钮间距
                button_layout.addWidget(edit_button)
                button_layout.addWidget(delete_button)
                button_layout.addWidget(complete_button)

                button_widget = QWidget()
                button_widget.setLayout(button_layout)
                self.table.setCellWidget(row, 7, button_widget)

                # 添加时间格式验证
                try:
                    datetime.strptime(appt['appointment_time'], "%Y-%m-%d %H:%M")
                except ValueError as e:
                    print(f"时间格式错误：{appt['appointment_time']}")

            self.table.viewport().update()
            QApplication.processEvents()

        except Exception as e:
            QMessageBox.critical(self, "错误", str(e))

    def show_create_dialog(self):
        dialog = QDialog(self)
        dialog.setObjectName("createDialog")
        dialog.setWindowTitle("新建预约")
        dialog.setWindowIcon(QIcon("assets/dialog_icon.svg"))
        dialog.setFixedSize(380, 300)  # 缩小弹框尺寸

        # 设置弹框样式
        dialog.setStyleSheet("""
            #createDialog {
                background-color: #ffffff;
                border-radius: 8px;
                padding: 20px; 
            }
            QLabel {
                color: #606266;
                font-size: 13px;  # 缩小字体
                min-width: 80px;
                margin-right: 8px;
            }
            QLineEdit, QDateTimeEdit {
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 6px 10px;  # 减少内边距
                font-size: 13px;  # 缩小字体
                min-height: 26px;
                min-width: 180px;  # 缩小宽度
            }
            QComboBox{
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 6px 10px;  # 减少内边距
                font-size: 13px;  # 缩小字体
                min-height: 14px;
                min-width: 180px;  # 缩小宽度
            }
        """)

        layout = QFormLayout(dialog)
        layout.setContentsMargins(25, 20, 25, 20)
        layout.setSpacing(15)

        # 客户信息
        name_input = QLineEdit()
        name_input.setPlaceholderText("请输入客户全名")
        phone_input = QLineEdit()
        # phone_input.setInputMask("99999999999;_")  # 11位纯数字输入
        phone_input.setMaxLength(11)
        phone_input.textChanged.connect(lambda: self.validate_phone(phone_input))
        phone_input.setPlaceholderText("请输入11位手机号")

        # 服务选择
        service_combo = QComboBox()
        service_combo.setStyleSheet("""
            QComboBox {
                min-width: 180px;  /* 与输入框宽度一致 */
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 6px 10px;
                font-size: 13px;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: right center;
                width: 20px;
                border-left: 1px solid #d0d0d0;
            }
        """)
        services = db.fetch_all("SELECT name FROM services")
        service_combo.addItems([s['name'] for s in services])

        # 理发师选择
        barber_combo = QComboBox()
        barber_combo.setIconSize(QSize(24, 24))
        barber_combo.setStyleSheet("""
            QComboBox {
                min-width: 180px;  /* 统一宽度 */
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 6px 10px;
                font-size: 13px;
            }
            QComboBox::item {
                padding: 6px 10px;  /* 增加选项内边距 */
            }
        """)
        barbers = db.fetch_all("SELECT id, display_name FROM users WHERE role = 'staff'")

        for barber in barbers:
            barber_combo.addItem(QIcon("assets/dialog_icon.svg"), barber['display_name'], barber['id'])

        # 预约时间
        time_edit = QDateTimeEdit()
        time_edit.setDateTime(QDateTime.currentDateTime().addSecs(3600))
        time_edit.setCalendarPopup(True)
        time_edit.setDisplayFormat("yyyy-MM-dd HH:mm")
        time_edit.setMinimumDateTime(QDateTime.currentDateTime())
        time_edit.setStyleSheet("""
            QDateTimeEdit {
                min-width: 180px;
                border: 1px solid #dcdfe6;
                border-radius: 4px;
                padding: 6px 10px;
                font-size: 13px;
            }
            QDateTimeEdit::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: right center;
                width: 20px;
                border-left: 1px solid #d0d0d0;
            }
            QCalendarWidget QToolButton {
                height: 24px;
                font-size: 12px;
            }
            QCalendarWidget QMenu {
                font-size: 12px;
            }
        """)

        # 修改表单行添加方式
        def add_form_row(layout, label, widget, icon_name=None):
            row = QHBoxLayout()
            row.setContentsMargins(0, 0, 0, 0)
            row.setSpacing(8)

            # 图标标签
            if icon_name:
                icon_label = QLabel()
                icon_path = f"assets/{icon_name}.svg"
                icon_label.setPixmap(QPixmap(icon_path).scaled(20, 20, Qt.KeepAspectRatio))
                icon_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)  # 左对齐
                row.addWidget(icon_label)

            # 标签和输入框容器
            content_widget = QWidget()
            content_layout = QHBoxLayout(content_widget)
            content_layout.setAlignment(Qt.AlignLeft)  # 左对齐
            content_layout.setContentsMargins(0, 0, 0, 0)
            content_layout.setSpacing(8)

            label_widget = QLabel(f"{label}:")
            label_widget.setFixedWidth(80)
            content_layout.addWidget(label_widget)
            content_layout.addWidget(widget)

            row.addWidget(content_widget)
            layout.addRow(row)

        add_form_row(layout, "客户姓名", name_input, "user")
        add_form_row(layout, "联系电话", phone_input, "phone")
        add_form_row(layout, "服务项目", service_combo, "service")
        add_form_row(layout, "理发师", barber_combo, "barber")
        add_form_row(layout, "预约时间", time_edit, "time")

        # 按钮样式优化
        button_style = """
            QPushButton {
                padding: 6px 16px;
                border-radius: 4px;
                font-size: 13px;
                min-width: 70px;
                min-height: 16px;
            }
        """

        # 确定取消按钮
        buttons = QHBoxLayout()
        buttons.setContentsMargins(0, 12, 0, 0)  # 增加顶部间距
        buttons.setSpacing(15)
        ok_btn = QPushButton("确定")
        cancel_btn = QPushButton("取消")

        # 应用按钮样式（修复拼接方式）
        ok_btn.setStyleSheet(f"""
            {button_style}
            QPushButton {{
                background-color: #4a90e2;
                color: white;
            }}
        """)
        cancel_btn.setStyleSheet(f"""
            {button_style}
            QPushButton {{
                background-color: #f0f0f0;
                color: #666;
            }}
        """)

        buttons.addStretch()
        buttons.addWidget(ok_btn)
        buttons.addWidget(cancel_btn)
        layout.addRow(buttons)

        ok_btn.clicked.connect(lambda: self.create_appointment(
            dialog, name_input.text(), phone_input.text(),
            service_combo.currentText(), barber_combo.currentData(),
            time_edit.dateTime()
        ))
        cancel_btn.clicked.connect(dialog.reject)

        dialog.exec()

    def validate_phone(self, input_field):
        phone = input_field.text().strip()
        if len(phone) != 11 or not phone.isdigit():
            input_field.setStyleSheet("border: 1px solid red;")
            return False
        else:
            input_field.setStyleSheet("")
            return True

    def create_appointment(self, dialog, name, phone, service, barber_id, appt_time):
        try:
            db.begin_transaction()  # 开始事务

            # 检查必填字段
            if not all([name.strip(), phone.strip(), service, barber_id]):
                raise ValueError("所有字段都必须填写")

            # 验证电话号码格式
            if len(phone) != 11 or not phone.isdigit():
                raise ValueError("电话号码必须为11位数字")

            # 检查时间冲突
            conflicts = db.fetch_all("""
                SELECT id FROM appointments 
                WHERE barber_id = ? AND appointment_time = ?
                AND status != 'completed'
            """, (barber_id, appt_time.toString("yyyy-MM-dd HH:mm")))

            if conflicts:
                raise ValueError("该时间段已有预约")

            # 插入数据
            success = db.execute("""
                INSERT INTO appointments 
                (customer_name, phone_number, service_type, barber_id, appointment_time, status)
                VALUES (?, ?, ?, ?, ?, ?)
            """, (
                name.strip(),
                phone,
                service,
                barber_id,
                appt_time.toString("yyyy-MM-dd HH:mm"),
                'pending'
            ))

            if not success:
                raise Exception("数据库插入失败")

            db.commit()  # 提交事务
            self.current_page = 1
            self.load_appointments()
            dialog.accept()

        except Exception as e:
            db.rollback()  # 回滚事务
            QMessageBox.critical(dialog, "错误", str(e))
            dialog.show()

    def delete_appointment(self, appt_id):
        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除这条预约记录吗？",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                db.execute("DELETE FROM appointments WHERE id = ?", (appt_id,))
                self.load_appointments()
            except Exception as e:
                QMessageBox.critical(self, "错误", str(e))

    def get_status_text(self, status):
        return {
            "pending": "待确认",
            "confirmed": "已确认",
            "completed": "已完成"
        }.get(status, status)

    def get_status_color(self, status):
        return {
            "pending": QColor(255, 165, 0),    # 橙色
            "confirmed": QColor(0, 128, 0),    # 绿色
            "completed": QColor(128, 128, 128)  # 灰色
        }.get(status, QColor(0, 0, 0))        # 默认黑色

    def apply_styles(self):
        self.setStyleSheet("""
            /* 统一修复所有QLineEdit样式 */
            QLineEdit {
                border: 1px solid #d0d0d0;
                border-radius: 3px;
                padding: 5px;
                background: white;
                font-size: 13px;
            }
            
            /* 修复QComboBox核心样式 */
            QComboBox {
                border: 1px solid #d0d0d0;
                border-radius: 3px;
                padding: 3px 6px;
                background: white;
                selection-background-color: #e6f3ff;
                min-height: 14px;
            }
            
            /* 修复下拉按钮样式 */
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: right center;
                width: 20px;
                border-left: 1px solid #d0d0d0;
                background: transparent;
            }
            
            /* 表格基础样式保持 */
            QTableWidget {
                border: 1px solid #e0e0e0;
                background-color: white;
            }
            
            QHeaderView::section {
                background-color: #f8f8f8;
                padding: 8px;
                border: none;
                border-bottom: 2px solid #e0e0e0;
                font-weight: bold;
                color: #606266;
            }
        """)

        # 设置表格行高
        self.table.verticalHeader().setDefaultSectionSize(40)  # 增加行高适应按钮

        # 隐藏垂直表头
        self.table.verticalHeader().setVisible(False)

        # 设置表格选择模式
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setSelectionMode(QTableWidget.SingleSelection)

    def change_page(self, delta):
        self.current_page += delta
        self.current_page = max(1, self.current_page)
        self.load_appointments()

    def delete_all_appointments(self):
        """
        用于测试删除所有预约
        """
        reply = QMessageBox.question(
            self, "确认删除所有预约",
            "确定要删除所有预约记录吗？",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                db.execute("DELETE FROM appointments")
                db.execute("DELETE FROM sqlite_sequence WHERE name='appointments'")
                self.load_appointments()
            except Exception as e:
                QMessageBox.critical(self, "错误", str(e))
